package march.finalmarch22.march03;

import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class Reducer03 extends Reducer<Text, Text,Text,NullWritable> {
    @Override
    protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {

        Map<String, Integer> map = new HashMap<>();

        String score = key.toString();
        //依据课程名进行遍历
        for (Text value : values) {
            String[] split = value.toString().split("\\|");
            String name = split[0];
            String[] split1 = split[2].split(",");

            //一名同学的全部放入Map中
            for (String s : split1) {
                map.put(name,Integer.parseInt(s));
            }
        }

        //该课程所有放入后，进行map排序，取前三即可
        ArrayList<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
        list.sort(((o1, o2) -> o2.getValue() - o1.getValue()));

        int i = 0;
        for (Map.Entry<String, Integer> entry : list) {

            String res = score+","+entry.getKey()+","+entry.getValue().toString();
            context.write(new Text(res),NullWritable.get());
            //输出排名前三
            i++;
            if (i == 3){
                break;
            }
        }

    }
}
